<?php

namespace app\controller;

use app\model\SupplierModel;
use app\model\UserCompanyModel;
use app\model\UserDepartmentRelationModel;
use think\Request;
use think\Response;
use think\facade\Db;

class UserManagement
{

    public function getList(Request $request)
    {
        $params = $request->param();

        $user = getUserInfo();
        $dataRole = dataPermissionCheck($user);
        $where = [];
        if ($dataRole == 'user') {
            $where[] = ['u.id', '=', $user['id']];
        } else if ($dataRole == 'company') {
            $where[] = ['u.company_id', '=', $user['company_id']];
        }

        $query = Db::name('user')
            ->where($where)
            ->alias('u')
            ->leftJoin('user_department_relation r', 'u.id = r.user_id')
            ->leftJoin('user_department d', 'r.department_id = d.id')
            ->leftJoin('company c', 'u.company_id = c.id')
            ->field([
                'u.*',
                'GROUP_CONCAT(d.id) as department_ids',
                'GROUP_CONCAT(d.name) as department_names',
                'GROUP_CONCAT(d.code) as department_codes',
                'GROUP_CONCAT(r.is_leading) as department_roles',
                'c.name as company_name'

            ])
            ->group('u.id');

        if (!empty($params['username'])) {
            $query->whereLike('u.username', '%' . $params['username'] . '%');
        }
        if (!empty($params['realname'])) {
            $query->whereLike('u.realname', '%' . $params['realname'] . '%');
        }
        if (isset($params['status']) && $params['status'] !== '') {
            $query->where('u.status', $params['status']);
        }

        $list = $query->paginate([
            'page' => $params['pageNo'] ?? 1,
            'list_rows' => $params['pageSize'] ?? 20,
            'query' => $params
        ]);

        $items = $list->items();
        foreach ($items as &$item) {
            $item['departments'] = [];

            if (!empty($item['department_ids'])) {
                $ids = explode(',', $item['department_ids']);
                $names = explode(',', $item['department_names']);
                $codes = explode(',', $item['department_codes']);
                $roles = explode(',', $item['department_roles']);

                // 创建部门ID到角色的映射
                $roleMap = [];
                for ($i = 0; $i < count($ids); $i++) {
                    $deptId = (int)$ids[$i];
                    $roleMap[$deptId] = (int)($roles[$i] ?? 2);
                }

                // 使用映射确保每个部门只出现一次
                $uniqueDepts = [];
                foreach ($ids as $index => $id) {
                    $deptId = (int)$id;
                    if (!isset($uniqueDepts[$deptId])) {
                        $uniqueDepts[$deptId] = [
                            'department_id' => $deptId,
                            'name' => $names[$index] ?? '',
                            'code' => $codes[$index] ?? '',
                            'is_leading' => $roleMap[$deptId] ?? 2
                        ];
                    }
                }

                $item['departments'] = array_values($uniqueDepts);
                $item['supplier_ids_name'] = SupplierModel::where('id','in',$item['supplier_ids'])->column('supplier_name');
            }

            // 查询用户权限
            $permissions = Db::name('user_permissions')
                ->where('user_id', $item['id'])
                ->column('permission');

            // 如果用户ID为1（管理员），返回所有权限
            if ($item['id'] == 1) {
                // 从数据库获取所有权限
                $permissions = Db::name('user_permissions')
                    ->group('permission')
                    ->column('permission');

                // 如果数据库中没有权限数据，给予基础权限
                if (empty($permissions)) {
                    $permissions = ['Index']; // 只允许访问首页
                }
            }

            $item['permissions'] = $permissions;

            // 添加调试日志
            error_log('用户ID: ' . $item['id'] . ', 权限: ' . json_encode($permissions));

            unset($item['department_ids'], $item['department_names'], $item['department_codes'], $item['department_roles']);
        }

        return json([
            'code' => 200,
            'data' => [
                'list' => $items,
                'total' => $list->total()
            ]
        ]);
    }

    public function doEdit(Request $request)
    {
        $data = $request->post();

        Db::startTrans();
        try {
            // 基础验证
            if (empty($data['username'])) {
                throw new \Exception('登录账号不能为空');
            }
            if (empty($data['realname'])) {
                throw new \Exception('真实姓名不能为空');
            }
            if (empty($data['id_card'])) {
                throw new \Exception('身份证号不能为空');
            }
            if (!preg_match('/^\d{17}[\dXx]$/', $data['id_card'])) {
                throw new \Exception('身份证号格式不正确');
            }
            if (empty($data['permissions'])) {
                throw new \Exception('请至少选择一个权限');
            }

            // 检查员工登录账号是否重复
            $nameExists = Db::name('user')
                    ->where('username', $data['username'])
                    ->when(!empty($data['id']), function ($query) use ($data) {
                        $query->where('id', '<>', $data['id']);
                    })
                    ->count() > 0;

            if ($nameExists) {
                throw new \Exception('登录账号已存在');
            }

            // 修复：正确处理密码字段 - 开始
            $password = isset($data['password']) ? $data['password'] : '';
            if (!empty($password)) {
                $password = password_hash($password, PASSWORD_BCRYPT);
            }
            // 修复：正确处理密码字段 - 结束

            // 准备用户数据
            $userData = [
                'username' => $data['username'],
                'realname' => $data['realname'],
                'id_card' => $data['id_card'],
                'gender' => $data['gender'] ?? 1,
                'nation' => $data['nation'] ?? '',
                'marital_status' => $data['marital_status'] ?? '',
                'address' => $data['address'] ?? '',
                'emergency_contact' => $data['emergency_contact'] ?? '',
                'emergency_phone' => $data['emergency_phone'] ?? '',
                'superior_id' => $data['superior_id'] ?? null,
                'supplier_ids' => $data['supplier_ids'] ?? '',
                'status' => $data['status'] ?? 1,
                'company_id' => $data['company_id'] ?? 0,
                'company_admin' => $data['company_admin'],
                'update_time' => date('Y-m-d H:i:s')
            ];

            // 只有密码非空时更新密码字段
            if (!empty($password)) {
                $userData['password'] = $password;
            }

            // 新增或更新用户
            if (empty($data['id'])) {
                $userData['create_time'] = date('Y-m-d H:i:s');
                $userId = Db::name('user')->insertGetId($userData);
                $action = '新增';
                error_log('新增用户，ID: ' . $userId);
            } else {
                $userId = $data['id'];
                Db::name('user')->where('id', $userId)->update($userData);
                $action = '更新';
                error_log('更新用户，ID: ' . $userId);
                // 删除旧的权限关系
                Db::name('user_permissions')->where('user_id', $userId)->delete();
                UserDepartmentRelationModel::where('user_id', $userId)->delete();
                UserCompanyModel::where('user_id', $userId)->delete();
            }

            // 处理权限关系
            $permissionRelations = [];
            foreach ($data['permissions'] as $permission) {
                $permissionRelations[] = [
                    'user_id' => $userId,
                    'permission' => $permission
                ];
            }


            if (!empty($permissionRelations)) {
                Db::name('user_permissions')->insertAll($permissionRelations);
            }

            if (!empty($data['department'])) {
                $department_data = [];
                foreach ($data['department'] as $v) {
                    $department_data[] = [
                        'user_id' => $userId,
                        'department_id' => $v,
                    ];
                }
                UserDepartmentRelationModel::insertAll($department_data);
            }

            if (!empty($data['company'])) {
                $company_data = [];
                foreach ($data['company'] as $v) {
                    $company_data[] = [
                        'user_id' => $userId,
                        'company_id' => $v,
                    ];
                }
                UserCompanyModel::insertAll($company_data);
            }


            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            error_log('保存失败: ' . $e->getMessage());
            return json([
                'code' => 500,
                'message' => $e->getMessage()
            ], 500);
        }

        return json([
            'code' => 200,
            'message' => $action . '成功'
        ]);
    }

    public function doDelete(Request $request)
    {
        // 修改：接收数组形式的ids参数
        $ids = $request->post('ids');

        // 确保ids是数组
        if (!is_array($ids)) {
            $ids = explode(',', $ids);
        }

        // 过滤空值和转换为整数
        $ids = array_filter(array_map('intval', $ids));

        if (empty($ids)) {
            return json([
                'code' => 500,
                'message' => '未提供要删除的用户ID'
            ], 500);
        }

        // 防止删除id=1的管理员
        if (in_array(1, $ids)) {
            return json([
                'code' => 500,
                'message' => '不能删除管理员账号'
            ], 500);
        }

        Db::startTrans();
        try {
            // 使用 whereIn 批量删除
            Db::name('user')->whereIn('id', $ids)->delete();
            Db::name('user_department_relation')->whereIn('user_id', $ids)->delete();
            Db::name('user_permissions')->whereIn('user_id', $ids)->delete();

            Db::commit();
            return json([
                'code' => 200,
                'message' => '删除成功'
            ]);

        } catch (\Exception $e) {
            Db::rollback();
            return json([
                'code' => 500,
                'message' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Notes: 获取所有的供应商接口
     * User: chenLei
     * Date: 10/28/25 11:41:51
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function supplierList()
    {
        $supplierModel = new SupplierModel();
        $res = $supplierModel->all();
        return json([
            'code' => 200,
            'data' => $res
        ]);
    }
}